package com.dk.util.http.interceptor;

import cn.hutool.json.JSONNull;
import cn.hutool.json.JSONUtil;
import com.dk.enumerate.HttpEnum;
import com.dk.util.json.JsonUtil;
import com.dk.util.log.Log;
import okhttp3.*;
import okio.Buffer;
import okio.BufferedSource;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * okhttp日志打印拦截器
 */
public class CustomLogInterceptor implements Interceptor {
    /**
     * 拦截打印日志方法
     * @param chain 拦截链对象
     * @return 响应对象
     * @throws IOException io异常
     */
    @Override
    public Response intercept(Chain chain) throws IOException {
        //获取请求对象
        Request request = chain.request();
        //获取响应对象
        Response response = chain.proceed(request);
        //打印
        printInfo(request, response);
        return response;
    }

    /**
     * 打印日志方法
     * @param request 请求对象
     * @param response 响应对象
     */
    private void printInfo(Request request, Response response) {
        String body = getResponseText(response);
        String logInfo = "http日志信息".concat(" \r\n ")
                .concat("请求Url-->:")
                .concat(request.method())
                .concat(" ")
                .concat(request.url().toString())
                .concat(" \r\n ")
                .concat("请求头-->:")
                .concat(getRequestHeaders(request))
                .concat(" \r\n ")
                .concat("请求体-->:")
                .concat(JsonUtil.formatJson(getRequestBody(request)))
                .concat(" \r\n ")
                .concat("响应码-->:")
                .concat(String.valueOf(response.code()))
                .concat(" \r\n ")
                .concat("响应头-->:")
                .concat(response.headers().toString())
                .concat(" \r\n ")
                .concat("响应结果-->:");
        if (request != null && response != null) {
            if(HttpEnum.GET.getValue().equals(request.method().toUpperCase())||HttpEnum.DELETE.getValue().equals(request.method().toUpperCase())){
                if(JSONUtil.isJson(body)){
                    logInfo = logInfo + JsonUtil.formatJson(body);
                }else{
                    logInfo = logInfo + body;
                }
            }else{
                logInfo = logInfo + JsonUtil.formatJson(getResponseText(response));
            }
        }
        Log.info(logInfo);
    }

    /**
     * 获取响应消息的文本信息
     * @param response 响应对象
     * @return 响应文本信息
     */
    private String getResponseText(Response response) {
        String str = "Empty!";
        try {
            //获取响应体对象
            ResponseBody body = response.body();
            //响应体不为空且大小不为0时,抽取响应消息字符
            if (body != null && body.contentLength() != 0) {
                BufferedSource source = body.source();
                source.request(Long.MAX_VALUE);
                Buffer buffer = source.buffer();
                MediaType mediaType = body.contentType();
                if (mediaType != null) {
                    @SuppressWarnings("CharsetObjectCanBeUsed") Charset charset = mediaType.charset(
                            Charset.forName("UTF-8"));
                    if (charset != null) {
                        str = buffer.clone().readString(charset);
                    }
                }
            }
        } catch (Exception e) {
            Log.error("-----获取响应文本失败,请求url"+response.request().url().toString()+";-----");
        }
        return str;
    }

    /**
     * 获取请求主体
     * @param request 请求对象
     * @return 请求参数字符串
     */
    private String getRequestBody(Request request) {
        String str = "Empty!";
        try {
            //获取请求体
            RequestBody body = request.body();
            //当请求体不为空时,抽取请求参数
            if (body != null) {
                Buffer buffer = new Buffer();
                body.writeTo(buffer);
                MediaType mediaType = body.contentType();
                if (mediaType != null) {
                    @SuppressWarnings("CharsetObjectCanBeUsed")
                    Charset charset = mediaType.charset(Charset.forName("UTF-8"));
                    if (charset != null) {
                        str = buffer.readString(charset);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

    /**
     * 获取请求头
     * @param request 请求对象
     * @return 请求参数
     */
    private String getRequestHeaders(Request request) {
        String str = "Empty!";
        //获取请求头对象
        Headers headers = request.headers();
        if (headers != null) {
            str = headers.toString();
        }
        return str;
    }

}